package cmj.cloudmusic.activity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.musicmodule.PlayApplication;
import com.example.musicmodule.entity.Music;
import com.example.musicmodule.ible.IMusic;
import com.example.musicmodule.ible.IPlayer;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cmj.cloudmusic.R;
import cmj.cloudmusic.view.ILrcBuilder;
import cmj.cloudmusic.view.ILrcView;
import cmj.cloudmusic.view.ILrcViewListener;
import cmj.cloudmusic.view.impl.DefaultLrcBuilder;
import cmj.cloudmusic.view.impl.LrcRow;

public class PlayActivity extends AppCompatActivity implements View.OnClickListener,IPlayer {
    private static final String TAG = "playhhee";
    PlayApplication application;
    IMusic player;

    AudioManager mAudioManager;
    int maxVolume;
    int currentVolume;

    LinearLayout lrcContaintor;
    FrameLayout normalContaintor;

    ImageButton back;
    ImageButton share;
    ImageButton playstop;
    ImageButton last;
    ImageButton next;
    //自定义LrcView，用来展示歌词
    ILrcView lrcView;

    SeekBar voice;
    //更新歌词的频率，每秒更新一次
    private int mPalyTimerDuration = 1000;
    //更新歌词的定时器
    private Timer mTimer;
    //更新歌词的定时任务
    private TimerTask mTask;
    //导航栏
    TextView musicTitle;
    TextView musicAuthor;
    //提示栏
    TextView currentTime;
    TextView totalTime;
    SeekBar seekBar;
    Timer timer;
    TimerTask task;
    boolean isChange;//state

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        application= (PlayApplication) getApplicationContext();
        application.iPlayer=this;
        player=application.music;
        initView();
        initTimer();
        update();
        bindEvent();
    }
    private void initView(){
        back= (ImageButton) findViewById(R.id.back);
        share= (ImageButton) findViewById(R.id.share);
        playstop= (ImageButton) findViewById(R.id.play_stop);
        last= (ImageButton) findViewById(R.id.last);
        next= (ImageButton) findViewById(R.id.next);
        musicTitle=(TextView)findViewById(R.id.musicname);
        musicAuthor=(TextView)findViewById(R.id.author);
        currentTime= (TextView) findViewById(R.id.time);
        totalTime= (TextView) findViewById(R.id.totaltime);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        lrcView= (ILrcView) findViewById(R.id.lrcview);


        lrcContaintor= (LinearLayout) findViewById(R.id.lrc);
        normalContaintor= (FrameLayout) findViewById(R.id.normalcon);

        lrcContaintor.setVisibility(View.GONE);

        voice= (SeekBar) findViewById(R.id.voice);
        //音量控制,初始化定义
       mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//最大音量
         maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//当前音量
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        voice.setMax(maxVolume);
        voice.setProgress(currentVolume);

        Log.e(TAG, "initView: "+maxVolume+"+++++++++++++++"+currentVolume );

        voice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //降低音量，调出系统音量控制
                if(currentVolume>progress){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0); //tempVolume:音量绝对值
//                    mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,
//                            AudioManager.FX_FOCUS_NAVIGATION_UP);
                }
                //增加音量，调出系统音量控制
                else {
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0); //tempVolume:音量绝对值
//                    mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,
//                            AudioManager.FX_FOCUS_NAVIGATION_UP);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    public void update(){
        if (application.music.isPlay()){
            playstop.setImageResource(R.drawable.play_pause_sel);
        }else {
            playstop.setImageResource(R.drawable.play_play_sel);
        }
        seekBar.setMax(player.getduration());
        totalTime.setText(mills2Time(player.getduration()));
        Music m=application.songList.get(application.songPosition);
        musicTitle.setText(m.getTitle());
        musicAuthor.setText(m.getAuthor());

    }

    private void initTimer(){
        //设置进度条长度

        if (timer==null){
            timer=new Timer();
            task=new TimerTask() {
                @Override
                public void run() {
                    //定时器执行：设置进度条
                    if(!isChange) {
                        seekBar.setProgress(player.getcurrenttime());
                    }
                }
            };
            timer.schedule(task,0,1000);
        }

    }
    private void bindEvent(){
        back.setOnClickListener(this);
        share.setOnClickListener(this);
        playstop.setOnClickListener(this);
        last.setOnClickListener(this);
        next.setOnClickListener(this);
        lrcContaintor.setOnClickListener(this);
        normalContaintor.setOnClickListener(this);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentTime.setText(mills2Time(progress));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChange=true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isChange=false;
                player.seek(seekBar.getProgress());
            }
        });
    }
    private String mills2Time(int time){
        String sTime="";
        int minite,secound;

        secound=time/1000;
        if (secound>60){
            minite=secound/60;
            secound=secound%60;
            if (secound<10){
                if (minite>9){
                    sTime=minite+":"+secound;
                }else {
                    sTime="0"+minite+":0"+secound;
                }
            }else {
                if (minite>9){
                    sTime=minite+":"+secound;
                }else {
                    sTime="0"+minite+":"+secound;
                }
            }

        }else if (secound<10){
            sTime="00:0"+secound;
        }else {
            sTime="00:"+secound;
        }
        return sTime;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        IMusic music=application.music;
        switch (v.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.share:
                break;
            case R.id.play_stop:
                if (music.isPlay()){
                playstop.setImageResource(R.drawable.play_play_sel);
                }else {
                    playstop.setImageResource(R.drawable.play_pause_sel);
                }
                music.pause();
                break;
            case R.id.last:
                music.prev();
                break;
            case R.id.next:
                music.next();
                break;
            case R.id.lrc:
                lrcContaintor.setVisibility(View.GONE);
                normalContaintor.setVisibility(View.VISIBLE);
                break;
            case R.id.normalcon:
                normalContaintor.setVisibility(View.GONE);
                lrcContaintor.setVisibility(View.VISIBLE);
                break;
        }
    }
    @Override
    public void setLrc(String lrc){
        //解析歌词构造器
        ILrcBuilder builder = new DefaultLrcBuilder();
        //解析歌词返回LrcRow集合
        List<LrcRow> rows = builder.getLrcRows(lrc);
        //将得到的歌词集合传给mLrcView用来展示
        lrcView.setLrc(rows);

        //设置自定义的LrcView上下拖动歌词时监听
        lrcView.setListener(new ILrcViewListener() {
            //当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
            public void onLrcSeeked(int newPosition, LrcRow row) {
                if (application.music != null) {
                    Log.d(TAG, "onLrcSeeked:" + row.time);
                    application.music.seek((int) row.time);
                }
            }
        });
    }
    @Override
    public void lrcShow(){
        if(mTimer == null){
            mTimer = new Timer();
            mTask = new LrcTask();
            mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
        }
    }
    /**
     * 展示歌曲的定时任务
     */
    class LrcTask extends TimerTask{
        @Override
        public void run() {
            //获取歌曲播放的位置
            final long timePassed = application.music.getcurrenttime();
            PlayActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    //滚动歌词
                    lrcView.seekLrcToTime(timePassed);
                }
            });

        }
    };

    @Override
    protected void onDestroy() {

        timer.cancel();
        timer=null;
        application.iPlayer=null;
        super.onDestroy();
    }
}
